package com.appspot.moviesessions.infrastructure.task;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import com.appspot.moviesessions.model.MovieCreatedEvent;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;

@Component("taskHandler")
public class TaskHandler implements ApplicationListener<ApplicationEvent> {

	private Queue taskQueue;

	@Autowired
	public TaskHandler(Queue taskQueue) {
		this.taskQueue = taskQueue;
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		if (event instanceof MovieCreatedEvent) {
			onMovieCreated((MovieCreatedEvent) event);

		}
	}

	private void onMovieCreated(MovieCreatedEvent event) {
		String movieName = event.getName();
		taskQueue.add(TaskOptions.Builder.withUrl("/update/movie").param(
		        "name", movieName).method(Method.GET));
	}

}
